package com.cdg.polymeric.core.ext.collectors;

import com.cdg.polymeric.AnnotationIncorrectException;
import com.cdg.polymeric.AnnotationSettingBuilder;
import com.cdg.polymeric.ReflectUtils;
import com.cdg.polymeric.annonation.PolymericFiled;
import com.cdg.polymeric.config.AnnotationSetting;
import com.cdg.polymeric.Collectors;
import com.cdg.polymeric.config.ClassAnnotationSetting;
import org.apache.ibatis.reflection.Reflector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;

public class PolymericFieldCollector implements Collectors {
    private static final Logger logger = LoggerFactory.getLogger(PolymericFieldCollector.class);
    private Reflector reflector = null;
    public PolymericFieldCollector(Reflector reflector){
        this.reflector = reflector;
    }


    /**
     * 默认收集基础配置
     * @return
     */
    @Override
    public void collect(CopyOnWriteArrayList<AnnotationSetting> annotationSettings) {
        if (Objects.nonNull(reflector)){
            AnnotationSettingBuilder annotationSettingBuilder  = new AnnotationSettingBuilder();
            List<Field> fields = ReflectUtils.findAllFields(reflector.getType());
            Class<?> vo = reflector.getType();
            for (Field field : fields){

              Class<?> fieldType = field.getType();
              Annotation[] annotations = field.getAnnotations();

              for (Annotation annotation : annotations){
                 if(annotation instanceof PolymericFiled){
                    String key = ((PolymericFiled) annotation).key();
                    String fieldName = field.getName();
                    Class<?> feignClass = ((PolymericFiled) annotation).feign();
                    String method = ((PolymericFiled) annotation).method();
                    Class<?>[] args = ((PolymericFiled) annotation).args();
                    boolean enabledCache = ((PolymericFiled) annotation).enableCache();
                    if (enabledCache){
                        AnnotationSetting annotationSetting = annotationSettingBuilder.key(key).feign(feignClass).method(method).args(args).enableCache(true).resultType(fieldType).build();
                        annotationSetting.setFieldName(fieldName);
                        annotationSettings.add(annotationSetting);
                    }else {
                        AnnotationSetting annotationSetting = annotationSettingBuilder.key(key).feign(feignClass).method(method).args(args).resultType(fieldType).build();
                        annotationSetting.setFieldName(fieldName);
                        annotationSettings.add(annotationSetting);
                    }

                 }

             }
            }

        }

    }

}
